<template>
	<view>
		<uni-popup ref="popup" title="配网" backgroundColor="white" :safeArea="false" type="bottom" @change="changePopup">
			<view style="padding: 40rpx 0">
				<view v-if="active === 0">

					<uni-notice-bar show-icon scrollable text="搜不到设备编号？配网失败？请点此处看教程" />

					<view v-if="startWifiError">
						<view>{{ startWifiError }}</view>
						<view class="btn-next" @click="startWifi">重试</view>
					</view>
					<view v-else>
						<view class="container" v-if="wifiInfo.ssid">
							<button class="button blue">设备编号</button>

							<view class="bg">
								<view v-for="(item,index) in bluetoothList" :key="index" class="bluetoothBox"
									v-if="bluetoothList.length>0">
									<view class="left">
										<view class="item_title">{{item.name}}</view>
									</view>
									<view v-if="connectDeviceId === item.deviceId" class="connect-btn"
										style="background-color: #3c3e49" @tap="closeBLEConnection(item.deviceId)">断开
									</view>
									<view v-else class="connect-btn" @tap="connect(item.deviceId,item.name)">连接</view>
								</view>
							</view>
							<view style="color: #2a90e8;font-weight: 500;font-size: 14px;">
								自动测试当前手机连接的WIFI名称</view>

							<view class="section">
								<view class="button1">wifi名称</view>
								<input class="inputwifi" v-model="wifiInfo.ssid" type="text" placeholder="请输入wifi名称" />
							</view>

							<view class="section">
								<view class="button1">wifi密码</view>
								<input class="inputwifi" v-model="wifiInfo.password" type="text"
									placeholder="请输入wifi密码" />
							</view>

						</view>
					</view>
				</view>

				<view>

				</view>
				<view>
					<view style="margin: 20rpx auto;" class="btn-next" @click="startConfiguration">开始配网</view>
					<view style="margin: 20rpx auto;" class="btn-next" @click="getDevInfo">开始小程序投影</view>
				</view>

			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		Blue
	} from '@/utils/index.js'
	import BlueLink from "@/components/BlueLink.vue";
	import {
		ConnectController
	} from '@/utils/controller.js'
	export default {
		props: {
			show: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			show: {
				handler(newVal, oldVal) {
					if (newVal) {
						this.showPopup()
					} else {
						if (oldVal) {
							this.closePopup()
						}
					}
				},
				immediate: true
			}
		},
		components: {
			BlueLink
		},
		data() {
			return {
				bluetoothList: [],
				connectDeviceId: '',
				showBlueLinkDialog: true,
				active: 0,
				blueConnectState: -1,
				stepsList: [{
					title: '设置wifi'
				}, {
					title: '连接设备蓝牙'
				}, {
					title: '开始配网'
				}],
				startWifiError: '',
				wifiInfo: {
					ssid: "",
					password: "",
					ip: "",
				},
				wifiList: [],
				timer: null,
				deviceid: "",
				deviceip: ""
			};
		},
		onLoad() {

		},
		onShow() {

			this.clearwifiordevice()

			this.startWifi()

			Blue.start()
			this.bluetoothList = Blue.deviceList
			this.connectDeviceId = Blue.bleConnectDeviceID

			ConnectController.addConnectStateListen(data => {
				console.log('监听连接==>', JSON.stringify(data))
				if (data.deviceId) {
					this.connectDeviceId = data.deviceId
				} else {
					this.connectDeviceId = null

				}

				// this.$emit('blueState', '来自子组件的数据');
			})
			const prefix = "YM_"; //彭工的测试模块
			ConnectController.addDevicesListen(device => {
				if (device.name && device.name.startsWith(prefix)) {
					const index = this.bluetoothList.findIndex(item => item.name === device.name)
					if (index < 0) {
						this.bluetoothList.push(device)
					}
				}
			})
		},
		methods: {
			changePopup(e) {
				if (e.show === false) {
					this.$emit('close')
				}
			},
			connect(id, name) {
				if (Blue.connectState === 200) {
					uni.showToast({
						icon: 'none',
						title: '蓝牙处于连接状态'
					})
					return
				}
				this.bleConnectDeviceID = id
				Blue.createBLEConnection(id, name)
			},
			closeBLEConnection() {
				uni.setStorageSync('bluename', "");
				this.bleConnectDeviceID = null
				Blue.closeBLEConnection()
			},
			clearwifiordevice() {
				uni.setStorageSync('ssid', '');
				uni.setStorageSync('password', '');
				this.active = 0
			},
			startBluetooth() {
				if (this.wifiInfo.ssid && this.wifiInfo.password) {
					this.active = 1
					this.getBlueState()
					this.showBlueLinkDialog = true
				} else {
					uni.showToast({
						icon: 'none',
						title: '请先配置WiFi'
					})
				}
			},
			startConfigurationPage() {
				if (this.blueConnectState === 200) {
					this.active = 2
				} else {
					uni.showToast({
						icon: 'none',
						title: '请先连接设备'
					})
				}
			},
			startConfiguration() {
				var that=this
				uni.showLoading({
					title: "设置网络..."
				})
				Blue.configWifi(this.wifiInfo.ssid, this.wifiInfo.password).then(res => {
					if (res == "设置网络完成") {
						uni.setStorageSync('ssid', this.wifiInfo.ssid);
						uni.setStorageSync('password', this.wifiInfo.password);
						setTimeout(() => {
							uni.hideLoading();
							
						}, 5000);
						
						uni.showToast({
							icon: 'none',
							title: "信息发送，请等待设备联网"
						})
						
						
					} else {
						setTimeout(() => {
							uni.hideLoading();
						}, 5000);
						uni.showToast({
							icon: 'none',
							title: "设置网络失败"
						})
					}
				})


			},
			startWifi() {
				console.log('开始初始化wifi========》')
				const _that = this
				_that.active = 0
				uni.startWifi({
					success(res) {
						console.log('初始化wifi成功:' + JSON.stringify(res))
						uni.getConnectedWifi({
							success(res) {
								console.log('获取wifi信息成功:' + JSON.stringify(res))
								console.log(res.wifi.SSID)
								_that.wifiInfo.ssid = res.wifi.SSID
							},
							fail(res) {
								console.error('获取wifi信息失败:' + JSON.stringify(res))
								switch (res.errCode) {
									case 12000:
										_that.startWifiError = "未先调用 startWifi 接口"
										break
									case 12001:
										_that.startWifiError = "当前系统不支持相关能力"
										break
									case 12002:
										_that.startWifiError = "密码错误"
										break
									case 12005:
										_that.startWifiError = "Android 特有，未打开 Wi-Fi 开关"
										break
									case 12012:
										_that.startWifiError =
											"系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试，仅 Android 支持"
										break
								}
							}
						})
					},
					fail(res) {
						console.error('初始化wifi失败:' + JSON.stringify(res))
					}
				})
			},
			getBlueState() {
				this.showBlueLinkDialog = false
				this.blueConnectState = Blue.connectState
			},
			getDevInfo() {
				uni.showLoading({
					title: "获取设备信息..."
				})
				Blue.getDeviceInfo().then(res => {
					console.log('获取设备信息:', res)
					if (res && res != "retry too") {
						setTimeout(() => {
							uni.hideLoading();
						}, 3000);
						uni.showToast({
							icon: 'none',
							title: "获取设备信息成功"
						})
						var tares = JSON.parse(res);
						this.deviceid = tares.id
						this.deviceip = tares.ip
						uni.setStorageSync('devip', this.deviceip);
						uni.setStorageSync('devid', this.deviceid);
						var devip = uni.getStorageSync('devip');
						var devid = uni.getStorageSync('devid');
						console.log(this.deviceid, this.deviceip)
						console.log(devip, devid)
						uni.switchTab({
							url: '/pages/tabbar/material/material'
						});

					} else {
						setTimeout(() => {
							uni.hideLoading();
						}, 3000);
						uni.showToast({
							icon: 'none',
							title: "获取设备信息失败"
						})
					}
				})

			}
		}
	}
</script>
<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.button1 {
		solid: #000;
		border-right: 1px solid black;
		width: 28%;
		padding: 30rpx 30rpx;
		font-size: 16px;
		text-align: center;
		color: black;
		display: inline-block;
	}

	.inputwifi {
		margin-left: 10px;
		font-size: 16px;
		text-align: center;
	}

	.button {
		width: 90%;
		font-size: 16px;
		text-align: center;
		border: none;
		border-radius: 5px;
		color: white;
	}

	.blue {
		background-color: #007BFF;
	}

	.gray {
		background-color: #6c757d;
	}

	.section {
		width: 90%;
		display: flex;
		flex-direction: row;
		align-items: center;
		border: 1px solid #000;
		border-radius: 10px;
		margin: 10px;
	}
</style>
<style lang="scss">
	page {
		background-color: white;
	}

	.title600 {
		text-align: center;
		font-size: 30px;
		font-weight: 600;
		padding-bottom: 30px;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		box-sizing: border-box;
		justify-content: space-around;
		display: flex;
		align-items: center;
		padding: 40rpx 0;
	}

	.item-wifi {
		height: 120rpx;
		margin: 20rpx;
		background-color: white;
		border-radius: 10rpx;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		display: flex;
		padding: 0 20rpx;
		align-items: center;
	}

	.connect-btn {
		width: 150rpx;
		height: 60rpx;
		background-color: #409EFF;
		color: white;
		border-radius: 30rpx;
		text-align: center;
		line-height: 60rpx;
		margin: auto 20rpx;
	}

	.btn-next {
		background-color: #3c96f3;
		color: white;
		width: 90%;
		height: 80rpx;
		text-align: center;
		line-height: 80rpx;
		border-radius: 40rpx
	}
</style>
<style lang="scss">
	.title600 {
		text-align: center;
		font-size: 30px;
		font-weight: 600;
		padding-bottom: 30px;
	}

	.bg {
		width: 100%;
		background-color: white;
		padding: 20rpx;
	}

	.bluetoothBox {
		height: 160rpx;
		background-color: white;
		border-radius: 10rpx;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		display: flex;
		align-items: center;
		margin: 0 20rpx;
		padding: 0 40rpx;
	}

	.bluetoothBox .left {
		flex: 1;
	}

	.item_title {
		font-size: 30rpx;
		color: #333;
		margin: 15rpx 0;
	}

	.item_subtitle {
		font-size: 26rpx;
		color: #666;
		margin: 15rpx 0;
	}

	.connect-btn {
		width: 150rpx;
		height: 60rpx;
		background-color: #409EFF;
		color: white;
		border-radius: 30rpx;
		text-align: center;
		line-height: 60rpx;
		margin: auto 20rpx;
	}
</style>